<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="500px"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm">
      <template #tagType="{ model, field }">
        <FormItemRest>
          <div class="flex gap-10px items-center">
            <Select
              :options="tagTypeOptions"
              v-model:value="model[field]"
              placeholder="请选择"
              style="width: 80px"
              showSearch
              optionFilterProp="label"
            />

            <Input
              v-model:value="dataRef['tagUrl']"
              placeholder="请输入"
              style="flex: 1"
              v-if="model[field] == 'link'"
            />
            <Select
              v-else
              style="flex: 1"
              :options="moduleList"
              v-model:value="dataRef['tagModuleCode']"
              placeholder="请选择"
              showSearch
              optionFilterProp="name"
              :field-names="{ label: 'name', value: 'code' }"
              @change="handleTagModuleCode"
            />
          </div>
        </FormItemRest>
      </template>
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref, onMounted } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema, tagTypeOptions } from './navigationTab.data';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { getVisualAddTag, getVisualModifyTag } from '/@/api/module/module';
  import { Form, Select, Input } from 'ant-design-vue';
  import { getModulesAll } from '/@/api/system/system';

  export default defineComponent({
    name: 'NavigationTabDrawer',
    components: { BasicDrawer, BasicForm, FormItemRest: Form.ItemRest, Select, Input },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const isUpdate = ref(true);
      let dataRef = ref<any>({});
      const formCode = ref('');
      const moduleList = ref<Recordable[]>([]);
      const [registerForm, { resetFields, setFieldsValue, validate, getFieldsValue }] = useForm({
        labelWidth: 110,
        schemas: formSchema,
        showActionButtonGroup: false,
      });

      const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
        resetFields();
        setDrawerProps({ confirmLoading: false });
        isUpdate.value = !!data?.isUpdate;
        formCode.value = data?.formCode ?? '';
        dataRef.value = {};
        if (unref(isUpdate)) {
          dataRef.value = data?.record;
        } else {
          dataRef.value = {
            tagType: 'module',
            tagOrder: data?.dataSourceLength ? data?.dataSourceLength + 1 : 1,
            code: data?.moduleCode,
            formCode: formCode.value,
          };
        }
        setFieldsValue({
          ...unref(dataRef),
        });
      });

      const getTitle = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));

      //类型change
      const handleTagModuleCode = (val) => {
        if (val) {
          const record = moduleList.value.find((item) => item.code == val);
          const values = getFieldsValue();
          if (!values.tagName) {
            setFieldsValue({ tagName: record!.name });
          }
        }
      };

      //获取所有模块
      const getModulesAllData = async () => {
        moduleList.value = (await getModulesAll()) || [];
      };

      onMounted(() => {
        getModulesAllData();
      });

      async function handleSubmit() {
        try {
          const values = await validate();
          let formDate = Object.assign({}, unref(dataRef), values);
          setDrawerProps({ confirmLoading: true });
          console.log(formDate);
          if (unref(isUpdate)) {
            await getVisualModifyTag(formDate);
          } else {
            formDate.tagNameAdd = formDate.tagName;
            await getVisualAddTag(formDate);
          }
          closeDrawer();
          emit('success');
        } finally {
          setDrawerProps({ confirmLoading: false });
        }
      }
      return {
        registerDrawer,
        registerForm,
        getTitle,
        handleSubmit,
        dataRef,
        tagTypeOptions,
        moduleList,
        handleTagModuleCode,
      };
    },
  });
</script>
